<div class="wrapper wrapper-content page-heading animated fadeInRight">
    <div class="row">
        <div class="col-lg-9">
            <div class="tabs-container">
                <ul class="nav nav-tabs" id="tab-list-2">
                    <li class="active" id="search-link"><a href="#search" data-toggle="tab" role="tab">Search</a></li>
                </ul>
                <div class="tab-content">
                    <div class="tab-pane active" id="search">
                        <div class="panel-body">
                                <div class="ibox-title" style="border: none;"><h5 style="color: #00afef"><i>Search</i></h5>
                                </div>
                                <div class="ibox-content">
                                    <form class="form-horizontal" id="payment_form_search">
                                        <div class="form-group">
                                            <label class="col-lg-4 control-label">Account #</label>
                                            <div class="col-lg-5">
                                               <input type="text" name="acct_num" class="form-control">
                                            </div>
                                        </div>
                                        <div class="form-group organization">
                                            <label class="col-lg-4 control-label">Account Name</label>
                                            <div class="col-lg-5">
                                                <input type="text" name="acct_name" class="form-control">
                                            </div>
                                        </div>
                                        <div class="form-group">
                                            <label class="col-lg-4 control-label"></label>
                                            <div class="col-lg-5">
                                                <a id="clear_tbl_result" href="javascript:document.getElementById('payment_form_search').reset();" class="btn btn-warning btn-md pull-right m-t-n-xs clear-btn"> Clear</a>
                                                <button type="button" class="btn btn-primary btn-md pull-right m-t-n-xs search-btn btn-margin-right" id="payment_searh"> Search</button>
                                                <i id="loading-icon-search" style="color: gray; display: none; margin-left: 50px;" class="fa fa-spinner fa-spin fa-lg"></i>
                                            </div>
                                        </div>
                                    </form>
                                    </div>
                                        <button id="add-form-tab" class="btn btn-success m-t-n-xs btn-md add-tab-btn" type="button"> Add</button>
                                <div class="ibox-content">
                                    <div class="table-responsive">
                                        <table data-limit-navigation="5" data-page-size="50" data-filter="#filter" data-page-navigation=".pagination" class="footable table-bordered" id="tbl_org" style="width:100%">
                                            <thead>
                                                <tr>
                                                    <th data-sort-ignore="false" data-type="numeric" >Invoice Number</th>
                                                    <th data-sort-ignore="true">Account Name</th>
                                                    <th data-sort-ignore="false" data-type="numeric" >Receipt #</th>
                                                    <th data-sort-ignore="true">Payment Date</th>
                                                    <th data-sort-ignore="true">Payment Type</th>
                                                    <th data-sort-ignore="false" data-type="numeric">Paid Amount</th>
                                                    <th data-sort-ignore="true" style="padding:8px;text-align:center;width:75px;">Action</th>
                                                </tr>
                                            </thead>
                                            <tbody id="result_payment">
                                            </tbody>
                                            <tfoot >
                                                <tr>
                                                    <td colspan="7" style='border: none !important;'>
                                                        <ul class="pagination pull-right"></ul>
                                                    </td>
                                                </tr>
                                            </tfoot>
                                        </table>
                                    </div>
                                </div>
                            </div><!--END OF iBox-->
                    </div>
                </div>
            </div>
        </div>
    </div><!-- END of class row-->
    <div class="modal inmodal" id="receipt" tabindex="-1" role="dialog" aria-hidden="true">
        <div style="width: 750px;" class="modal-dialog">
            <div class="modal-content animated fadeInUp">
                    <div id="receipt_modal_load" class="sk-spinner sk-spinner-wave">
                        <div class="sk-rect1"></div>
                        <div class="sk-rect2"></div>
                        <div class="sk-rect3"></div>
                        <div class="sk-rect4"></div>
                        <div class="sk-rect5"></div>
                    </div>
                    <div class="modal-body">
                        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                        <h2 style="color: #00afef"><i>Payment Details</i></h2>
                        <br>
                        <form class="form-horizontal" id="receipt_payment_form">
                            <div class="form-inline form-group">
                                <label class="col-sm-2 control-label">Receipt No</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="receipt_number" class="form-control">
                                </div>
                                <label class="col-sm-3 control-label">Payment Type</label>
                                <div class="col-sm-3">
                                    <input type="hidden" name="totalcost" value="">
                                    <input readonly type="text" id="payment_type" class="form-control">
                                </div>
                            </div>
                            <div class="form-inline form-group">
                                <label class="col-sm-2 control-label">Receipt Date</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="receipt_date" class="form-control">
                                </div>
                                <label class="col-sm-3 control-label">Account No</label>
                                <div class="col-sm-3">
                                    <input readonly type="text" id="acct_no" class="form-control">
                                </div>
                            </div>
                            <div class="form-group form-inline">
                                <label class="col-sm-2 control-label">Reference</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="reference" class="form-control">
                                </div>
                                 <label class="col-sm-3 control-label">Total Selected Amt</label>
                                <div class="col-sm-3">
                                    <input readonly type="text" id="total_selectedss" class="form-control">
                                </div>
                            </div>
                            <div class="form-group form-inline">
                                <label class="col-sm-2 control-label">Receipt Amount</label>
                                <div class="col-lg-3">
                                    <input readonly type="text" id="main_receipt_amt" class="form-control">
                                </div>
                                <label class="col-sm-3 control-label">Unapplied Payments</label>
                                <div class="col-sm-3">
                                    <input readonly type="text" id="unapp_pay" class="form-control">
                                </div>
                            </div>
                        </form>
                        <br>
                        <center>
                        <div id="payment_details_body">
                        <table class="c-table">
                            <thead>
                                <tr>
                                    <th>Invoice Number</th>
                                    <th>Invoice Type</th>
                                    <th>Invoice Date</th>
                                    <th>Due Date</th>
                                    <th>Unpaid Amt</th>
                                    <th>Paid Amt</th>
                                </tr>
                            </thead>
                            <tbody id="receipt_tbl">
                            </tbody>
                        </table>
                        </div>
                        <br>
                        <div style="width: 250px;">
                           <button type="button" class="btn btn-success btn-block btn-md m-t-n-xs" id="pr"><i class="fa fa-print fa-fw"></i> Print Receipt</button>
                        </div>
                        </center>
                        <br>
                        <br>
                    </div>
                </div>
            </div>
        </div>
</div>
<input type="hidden" id="ac_name" value="">
<input type="hidden" id="count_add" value="0">
<input type="hidden" id="count_edit" value="0">
<input type="hidden" id="count_view" value="0">
<script>
    $(document).ready(function() {
        var tmp2 = ''; var cname; var tap;
        $('#clear_tbl_result').click(function(){
            $('#result_payment').html('');
        });
        $('#tab-list-2').on('click','#close-add-body',function(){
            var tabId = $(this).parents('li').children('a').attr('href');
            // $(this).parents('li').remove('li');
            // $(tabId).remove();
            // $('#tab-list a:first').tab('show');
            if(tabId == "#view"){
                $('#count_view').val('0');
                $(this).parents('li').remove('li');
                $(tabId).remove();
                $('#tab-list-2 a:first').tab('show');
            }else{
                alert_cancel(tabId,$(this));
            }
        });

        $('#pr').click(function(){

           var wordAmt =  toWords(tap);
           console.log(wordAmt + " name : "  + $('#ac_name').val());
           
            //printHex(tmp2,$('#receipt_payment_form #receipt_number').val(),$('#receipt_payment_form #acct_no').val(),$('#receipt_payment_form #payment_type').val(),$('#receipt_payment_form #receipt_date').val(),$('#receipt_payment_form #reference').val());
        });

        function alert_cancel(tabId,btn){
                    swal({
                      title: "Are you sure?",
                      text: "Your work will not be save",
                      type: "warning",
                      showCancelButton: true,
                      confirmButtonColor: "#DD6B55",
                      confirmButtonText: "Leave",
                      cancelButtonText: "Stay",
                      closeOnConfirm: true,
                      closeOnCancel: true },
                  function (isConfirm) {
                      if (isConfirm) {
                        swal("success");
                        $(btn).parents('li').remove('li');
                        $(tabId).remove();
                        $('#tab-list-2 a:first').tab('show');
                        if(tabId == "#edit"){
                            $('#count_edit').val('0');
                        }else{
                            $('#count_add').val('0');
                        }
                      } else {
                        swal("Cancelled");
                      }
                });
            }
        $('#payment_form_search').keydown(function (e) {
          if (e.which == 13) {
            $('#payment_form_search #payment_searh').trigger('click');
            return false;  
          }
        });
        $('#payment_searh').click(function(){
            var cname="";
            $.ajax({
                url: "<?php echo base_url($this->session->userdata('forajax') . '/search'); ?>",
                method: 'post',
                timeout: 8000,
                data:$('#payment_form_search').serialize(),
                dataType:'json',
                success: function (data) {
                    if(data !== 'No results found.'){
                        console.log(data);
                        $('#')
                        var tmp = '';
                        var count = 0;
                        $.each(data,function(i,item) {
                            var pay_amount = parseFloat(data[i].pay_amount);
                            //<button class="btn btn-sm btn-info btn-outline btn-xs view-link" id="'+data[i].payment_id+'" type="button" title="View"><i class="fa fa-file-text-o"></i></button>&nbsp;
                            tmp += '<tr><td align="right">'+ data[i].invoice_num +'</td><td>'+ data[i].acct_name +'</td><td align="right">'+ data[i].receipt_number +'</td><td>'+ data[i].receipt_date +'</td><td>'+ data[i].payment_type +'</td><td align="right">'+ pay_amount.toFixed(2) +'</td><td align="center"><button class="btn btn-sm btn-primary btn-outline btn-xs rec-link" id="'+data[i].receipt_number+'" type="button" title="Print"><i class="fa fa-print"></i></button></td></tr>';
                            $('#ac_name').val(data[i].acct_name);
                            count++;
                        });
                        notifymsg('success','<b>Success</b>: '+count+ ' Result(s) Found.');
                    }else{
                        notifymsg('success','<b>Success</b>: 0 Result(s) Found.');
                        tmp += '<tr align="center"><td colspan="7">No Result(s)</td></tr>'
                    }
                    $('#result_payment').html(tmp).trigger('footable_redraw');
                },
                complete: function() {
                    $("#payment_searh").removeAttr("disabled");
                    $('#loading-icon-search').hide();
                },
                beforeSend: function(){
                    $("#payment_searh").attr("disabled", true);
                    $('#loading-icon-search').show();
                },
                error: function(x, t, m) {
                        if(t === "timeout") {
                            notifymsg('error','<b>Error</b>: Request Timeout.');
                        } else {
                            notifymsg('error','<b>Error</b>: ' + t);
                        }
                    }
            });
        });

        $('#add-form-tab').click(function(){
             if($('#count_add').val() == 0){
                $('#tab-list-2').append('<li id="add-link"><a href="#add" role="tab" data-toggle="tab">New Payments<button id="addX" style="margin-left:10px;"class="close" type="button" title="Remove this page">×</button></a></li>');
                $('.tab-content').append('<div class="tab-pane" id="add"><div class="panel-body"><div id="add_data"><div class="sk-spinner sk-spinner-double-bounce"><div class="sk-double-bounce1"></div><div class="sk-double-bounce2"></div></div></div></div></div>');
                $('#add-link').show();
                $('#count_add').val('1');
            }
            $('#tab-list-2 a[href="#add"]').tab('show');
            $("#add_data").load("<?php echo $this->session->userdata('forload') . '/add_form/'; ?>",function(response, status, xhr) {
              if (status == "error") {
                    var msg = "Sorry but there was an error: ";
                    notifymsg('danger',msg + xhr.status + " " + xhr.statusText);
                  }
              });
        });

        $(document).on('click','.view-link',function(){
             var id = $(this).attr('id');
             if($('#count_view').val() == 0){
                $('#tab-list-2').append('<li id="view-link"><a href="#view" role="tab" data-toggle="tab">Payment Details<button id="close-add-body" style="margin-left:10px;"class="close" type="button" title="Remove this page">×</button></a></li>');
                $('.tab-content').append('<div class="tab-pane" id="view"><div class="panel-body"><div id="view_data"><div class="sk-spinner sk-spinner-double-bounce"><div class="sk-double-bounce1"></div><div class="sk-double-bounce2"></div></div></div></div></div>');
                $('#view-link').show();
                $('#count_view').val('1');
            }
            $('#tab-list-2 a[href="#view"]').tab('show');
            $("#view_data").load("<?php echo $this->session->userdata('forload') . '/view_form/'; ?>" + id,function(response, status, xhr) {
              if (status == "error") {
                    var msg = "Sorry but there was an error: ";
                    notifymsg('danger',msg + xhr.status + " " + xhr.statusText);
                  }
              });
        });

        $(document).on('click','.rec-link',function(){
            var id = $(this).attr('id');
            getReceipt(id);
        });

        function getReceipt(id){
            tap = 0.00;
            $('#receipt').modal('show');
            $.ajax({
                url: "<?php echo base_url($this->session->userdata('forajax') . '/getReceipt'); ?>",
                method: 'post',
                data: { 'receipt_number' : id },
                dataType:'json',
                success: function (data) {
                    if(data !== 'No results found.'){
                        $('#receipt_payment_form #receipt_number').val(data[0].receipt_number);
                        $('#receipt_payment_form #acct_no').val(data[0].acct_num);
                        $('#receipt_payment_form #payment_type').val(data[0].payment_type);
                        $('#receipt_payment_form #receipt_date').val(data[0].receipt_date);
                        $('#receipt_payment_form #reference').val(data[0].reference);
                        $('#receipt_payment_form #total_selectedss').val(data[0].selected_amt);
                        $('#receipt_payment_form #main_receipt_amt').val(data[0].pay_amount);
                        var tmp = '';
                        var sum_pay = 0;
                        $.each(data,function(i,item) {
                            tmp += '<tr><td align="right">'+ data[i].invoice_num +'</td><td align="right">'+ data[i].invoice_type +'</td><td>'+ data[i].invoice_date +'</td><td align="right">'+ data[i].due_date +'</td><td align="right">'+ data[i].unpaid_amt +'</td><td align="right">'+ data[i].pay_amount +'</td></tr>';
                            tap = tap + parseInt(data[i].pay_amount);                       
                        });
                        tmp2 = tmp;
                    }else{
                        tmp += '<tr align="center"><td colspan="7">No Result(s)</td></tr>'
                    }
                    $('#receipt_tbl').html(tmp);
                    gen_advance_row_main(id);
                },
                beforeSend: function(){
                    $('#receipt_modal_load').show();
                    $('#receipt .modal-body').hide();
                },
                complete: function(){
                    $('#receipt .modal-body').show();
                    $('#receipt_modal_load').hide();
                },
                error: function(response, status, xhr) {
                  if (status == "error") {
                        var msg = "Sorry but there was an error: ";
                        $('#receipt .modal-body').html(msg + xhr.status + " " + xhr.statusText);
                        $('#receipt_modal_load').hide();
                    }
                }
            });
            
        }

        function gen_advance_row_main(id){
            var unapp =0;
         $.ajax({
                url: "<?php echo base_url($this->session->userdata('forajax') . '/genAdvance'); ?>",
                method: 'post',
                data: { 'receipt_number' : id },
                dataType:'json',
                success: function (data) {
                    if(data !== 'No results found.'){
                        var tmp = '';
                        var sum_pay = 0;
                        $.each(data,function(i,item) {
                            tmp += '<tr><td align="right">Advance Payment</td><td align="right"></td><td></td><td align="right"></td><td align="right"></td><td align="right">'+ data[i].applied_amt +'</td></tr>'; unapp = parseFloat(unapp) + parseFloat(data[i].applied_amt);
                        });
                    }else{
                        tmp += '<tr align="center"><td colspan="7">No Result(s)</td></tr>'
                    }
                    $('#receipt_tbl').append(tmp);
                    $('#unapp_pay').val(unapp);
                },
                beforeSend: function(){
                    $('#receipt_modal_load').show();
                    $('#receipt .modal-body').hide();
                },
                complete: function(){
                    $('#receipt .modal-body').show();
                    $('#receipt_modal_load').hide();
                },
                error: function(response, status, xhr) {
                  if (status == "error") {
                        var msg = "Sorry but there was an error: ";
                        $('#receipt .modal-body').html(msg + xhr.status + " " + xhr.statusText);
                        $('#receipt_modal_load').hide();
                    }
                }
            });   
        }


    });
</script>
<script type="text/javascript">

/**
 * Re-use the new WebSockets deployment if available.  If not, fallback on the Oracle deployment
 */
window["deployQZ"] = typeof(deployQZ) == "function" ? deployQZ : deployQZApplet;

function deployQZApplet() {
    console.log('Starting deploy of qz applet');

    var attributes = {id: "qz", code:'qz.PrintApplet.class',
        archive:'../qz-print.jar', width:1, height:1};
    var parameters = {jnlp_href: '../qz-print_jnlp.jnlp',
        cache_option:'plugin', disable_logging:'false',
        initial_focus:'false', separate_jvm:'true'};
    if (deployJava.versionCheck("1.7+") == true) {}
    else if (deployJava.versionCheck("1.6.0_45+") == true) {}
    else if (deployJava.versionCheck("1.6+") == true) {
        delete parameters['jnlp_href'];
    }

    // Disable java download redirects
    // deployJava.installJRE = function(version, ignore) { alert("Java " + version + " NPAPI plugin not available"); }
    // deployJava.runApplet(attributes, parameters, '1.6');
}

/**
 * Deploy tray version of QZ, or
 * Optionally used to deploy multiple versions of the applet for mixed
 * environments.  Oracle uses document.write(), which puts the applet at the
 * top of the page, bumping all HTML content down.
 */
deployQZ();

function getCertificate(callback) {
    
    $.ajax({
        method: 'GET',
        url: 'assets/auth/localhost.txt',
        async: false,
        success: callback // Data returned from ajax call should be the site certificate
    });
    

    //Non-ajax method, only include public key and intermediate key
    callback("-----BEGIN CERTIFICATE-----\n" +
        "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\n" +
        "-----END CERTIFICATE-----\n" +
        "--START INTERMEDIATE CERT--\n" +
        "-----BEGIN CERTIFICATE-----\n" +
        "MIIFEjCCA/qgAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwgawxCzAJBgNVBAYTAlVT\n" +
        "MQswCQYDVQQIDAJOWTESMBAGA1UEBwwJQ2FuYXN0b3RhMRswGQYDVQQKDBJRWiBJ\n" +
        "bmR1c3RyaWVzLCBMTEMxGzAZBgNVBAsMElFaIEluZHVzdHJpZXMsIExMQzEZMBcG\n" +
        "A1UEAwwQcXppbmR1c3RyaWVzLmNvbTEnMCUGCSqGSIb3DQEJARYYc3VwcG9ydEBx\n" +
        "emluZHVzdHJpZXMuY29tMB4XDTE1MDMwMjAwNTAxOFoXDTM1MDMwMjAwNTAxOFow\n" +
        "gZgxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJOWTEbMBkGA1UECgwSUVogSW5kdXN0\n" +
        "cmllcywgTExDMRswGQYDVQQLDBJRWiBJbmR1c3RyaWVzLCBMTEMxGTAXBgNVBAMM\n" +
        "EHF6aW5kdXN0cmllcy5jb20xJzAlBgkqhkiG9w0BCQEWGHN1cHBvcnRAcXppbmR1\n" +
        "c3RyaWVzLmNvbTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBANTDgNLU\n" +
        "iohl/rQoZ2bTMHVEk1mA020LYhgfWjO0+GsLlbg5SvWVFWkv4ZgffuVRXLHrwz1H\n" +
        "YpMyo+Zh8ksJF9ssJWCwQGO5ciM6dmoryyB0VZHGY1blewdMuxieXP7Kr6XD3GRM\n" +
        "GAhEwTxjUzI3ksuRunX4IcnRXKYkg5pjs4nLEhXtIZWDLiXPUsyUAEq1U1qdL1AH\n" +
        "EtdK/L3zLATnhPB6ZiM+HzNG4aAPynSA38fpeeZ4R0tINMpFThwNgGUsxYKsP9kh\n" +
        "0gxGl8YHL6ZzC7BC8FXIB/0Wteng0+XLAVto56Pyxt7BdxtNVuVNNXgkCi9tMqVX\n" +
        "xOk3oIvODDt0UoQUZ/umUuoMuOLekYUpZVk4utCqXXlB4mVfS5/zWB6nVxFX8Io1\n" +
        "9FOiDLTwZVtBmzmeikzb6o1QLp9F2TAvlf8+DIGDOo0DpPQUtOUyLPCh5hBaDGFE\n" +
        "ZhE56qPCBiQIc4T2klWX/80C5NZnd/tJNxjyUyk7bjdDzhzT10CGRAsqxAnsjvMD\n" +
        "2KcMf3oXN4PNgyfpbfq2ipxJ1u777Gpbzyf0xoKwH9FYigmqfRH2N2pEdiYawKrX\n" +
        "6pyXzGM4cvQ5X1Yxf2x/+xdTLdVaLnZgwrdqwFYmDejGAldXlYDl3jbBHVM1v+uY\n" +
        "5ItGTjk+3vLrxmvGy5XFVG+8fF/xaVfo5TW5AgMBAAGjUDBOMB0GA1UdDgQWBBSQ\n" +
        "plC3hNS56l/yBYQTeEXoqXVUXDAfBgNVHSMEGDAWgBQDRcZNwPqOqQvagw9BpW0S\n" +
        "BkOpXjAMBgNVHRMEBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAJIO8SiNr9jpLQ\n" +
        "eUsFUmbueoxyI5L+P5eV92ceVOJ2tAlBA13vzF1NWlpSlrMmQcVUE/K4D01qtr0k\n" +
        "gDs6LUHvj2XXLpyEogitbBgipkQpwCTJVfC9bWYBwEotC7Y8mVjjEV7uXAT71GKT\n" +
        "x8XlB9maf+BTZGgyoulA5pTYJ++7s/xX9gzSWCa+eXGcjguBtYYXaAjjAqFGRAvu\n" +
        "pz1yrDWcA6H94HeErJKUXBakS0Jm/V33JDuVXY+aZ8EQi2kV82aZbNdXll/R6iGw\n" +
        "2ur4rDErnHsiphBgZB71C5FD4cdfSONTsYxmPmyUb5T+KLUouxZ9B0Wh28ucc1Lp\n" +
        "rbO7BnjW\n" +
        "-----END CERTIFICATE-----\n");
}

function signRequest(toSign, callback) {
    
    $.ajax({
        method: 'GET',
        contentType: "text/plain",
        url: '/cs/assets/signing/sign-message.php?request=' + toSign,
        async: false,
        success: callback // Data returned from ajax call should be the signature
    });
    

    //Send unsigned messages to socket - users will then have to Allow/Deny each print request
    // callback();
}


/**
 * Automatically gets called when applet has loaded.
 */
function qzReady() {
    // If the qz object hasn't been created, fallback on the <applet> tags
    if (!qz) {
        window["qz"] = document.getElementById('qz');
    }
    var version = document.getElementById("version");
    if (qz) {
        try {
            version.innerHTML = qz.getVersion();
            document.getElementById("qz-status").style.background = "#F0F0F0";
        } catch(err) { // LiveConnect error, display a detailed message
            document.getElementById("qz-status").style.background = "#F5A9A9";
            alert("ERROR:  \nThe applet did not load correctly.  Communication to the " +
                    "applet has failed, likely caused by Java Security Settings.  \n\n" +
                    "CAUSE:  \nJava 7 update 25 and higher block LiveConnect calls " +
                    "once Oracle has marked that version as outdated, which " +
                    "is likely the cause.  \n\nSOLUTION:  \n  1. Update Java to the latest " +
                    "Java version \n          (or)\n  2. Lower the security " +
                    "settings from the Java Control Panel.");
        }
    }
}

function launchQZ() {
    if (window["qz"] && $.isFunction(qz.isActive) && qz.isActive()) {
        alert("Already running");
    } else {
        window.location.assign("qz:launch");
        qzNoConnection = function() { deployQZ(); }
        qzNoConnection();
    }
}

function qzSocketError(event) {
    document.getElementById("qz-status").style.background = "#F5A9A9";
    console.log('Error:');
    console.log(event);

    alert("Connection had an error:\n"+ event.reason);
}

function qzSocketClose(event) {
    document.getElementById("qz-status").style.background = "#A0A0A0";
    console.log('Close:');
    console.log(event);
    qz = null;

    alert("Connection was closed:\n"+ event.reason);
}

function qzNoConnection() {
    alert("Unable to connect to QZ, is it running?");

    //run deploy applet After page load
    var content = '';
    var oldWrite = document.write;
    document.write = function(text) {
        content += text;
    };
    deployQZApplet();

    var newElem = document.createElement('ins');
    newElem.innerHTML = content;

    document.write = oldWrite;
    document.body.appendChild(newElem);
}


/**
 * Returns is the applet is not loaded properly
 */
function isLoaded() {
    if (!qz) {
        alert('Error:\n\n\tPrint plugin is NOT loaded!');
        return false;
    } else {
        try {
            if (!qz.isActive()) {
                alert('Error:\n\n\tPrint plugin is loaded but NOT active!');
                return false;
            }
        } catch (err) {
            alert('Error:\n\n\tPrint plugin is NOT loaded properly!');
            return false;
        }
    }
    return true;
}

/**
 * Automatically gets called when "qz.print()" is finished.
 */
function qzDonePrinting() {
    // Alert error, if any
    if (qz.getException()) {
        alert('Error printing:\n\n\t' + qz.getException().getLocalizedMessage());
        qz.clearException();
        return;
    }

    // Alert success message
    alert('Successfully sent print data to "' + qz.getPrinter() + '" queue.');
}

/***************************************************************************
 * Prototype function for finding the "default printer" on the system
 * Usage:
 *    qz.findPrinter();
 *    window['qzDoneFinding'] = function() { alert(qz.getPrinter()); };
 ***************************************************************************/
function useDefaultPrinter() {
    if (isLoaded()) {
        // Searches for default printer
        qz.findPrinter();

        // Automatically gets called when "qz.findPrinter()" is finished.
        window['qzDoneFinding'] = function() {
            // Alert the printer name to user
            var printer = qz.getPrinter();
            alert(printer !== null ? 'Default printer found: "' + printer + '"':
            'Default printer ' + 'not found');

            // Remove reference to this function
            window['qzDoneFinding'] = null;
        };
    }
}





/***************************************************************************
 * Prototype function for finding the closest match to a printer name.
 * Usage:
 *    qz.findPrinter('zebra');
 *    window['qzDoneFinding'] = function() { alert(qz.getPrinter()); };
 ***************************************************************************/
function findPrinter() {
    // Get printer name from input box

    if (isLoaded()) {
        // Searches for locally installed printer with specified name
        qz.findPrinter('Epson');

        // Automatically gets called when "qz.findPrinter()" is finished.
        window['qzDoneFinding'] = function() {
            var p = document.getElementById('printer');
            var printer = qz.getPrinter();

            // Alert the printer name to user
          

            // Remove reference to this function
            window['qzDoneFinding'] = null;
        };
    }

    
}


function notReady() {
    // If applet is not loaded, display an error
    if (!isLoaded()) {
        return true;
    }
    // If a printer hasn't been selected, display a message.
    else if (!qz.getPrinter()) {
      findPrinter();
    }
    return false;
}

/***************************************************************************
 * Prototype function for printing hexadecimal formatted raw data
 *
 * Usage:
 *    qz.appendHex('00AABBCCDDEEFF');
 *    qz.appendHex('x00xAAxBBxCCxDDxEExFF');
 *    qz.print();
 ***************************************************************************/
function printHex(tmp2,rn,an,pt,pd,rf) {

    if (notReady()) { return; }

    qz.setCopies(1);


    // Append our image (only one image can be appended per print)
    qz.appendHTML(
            '<html><body>' +
                '<table>'+
                '<tr>' +   
                '<td><span> Receipt No   : ' + rn + '</span></td>' +
                '<td><span> Account No   : ' + an + '</span></td>' +
                '</tr><tr>' +
                '<td><span> Payment Type : ' + pt + '</span></td>' + 
                '<td><span> Payment Date : ' + pd + '</span></td>' +
                '</tr><tr>' +
                '<td><span> Reference No : ' + rf +'</span></td>' +
                '</tr>' +
                '</table>' +
                '<table face="monospace" border="1px">' +
                '<tr height="6cm">' +
                    '<td valign="top"> Invoice Number </td>' +
                    '<td valign="top"> Invoice Type </td>' +
                    '<td valign="top"> Invoice Date </td>' +
                    '<td valign="top"> Due Date</td>' +
                    '<td valign="top"> Unpaid Amt </td>' +
                    '<td valign="top"> Paid Amt </td>' +
                    '<td valign="top"> Balance </td>' +
                '</tr>' + tmp2 +
                '</table>'+
            '</body></html>'
    );

    qz.printHTML();

   // qz.appendHex("4e0d0a713630390d0a513230332c32360d0a42352c32362c");
   //  qz.appendHex("302c31412c332c372c3135322c422c2231323334220d0a41");
   //  qz.appendHex("3331302c32362c302c332c312c312c4e2c22534b55203030");
   //  qz.appendHex("303030204d46472030303030220d0a413331302c35362c30");
   //  qz.appendHex("2c332c312c312c4e2c22515a205072696e7420506c756769");
   //  qz.appendHex("6e220d0a413331302c38362c302c332c312c312c4e2c2254");
   //  qz.appendHex("657374207072696e74207375636365737366756c220d0a41");
   //  qz.appendHex("3331302c3131362c302c332c312c312c4e2c2266726f6d20");
   //  qz.appendHex("73616d706c652e68746d6c220d0a413331302c3134362c30");
   //  qz.appendHex("2c332c312c312c4e2c227072696e7448657828292066756e");
   //  qz.appendHex("6374696f6e2e220d0a50312c310d0a");

   //  // Send characters/raw commands to printer
   //  qz.print();
    // Since 1.5.4, No backslashes needed (fixes \x00 NUL JavaScript bug)
    // Can be in format "1B00" or "x1Bx00"
    // EPL Sample Provided

}



</script>
<!--

    -- Receipt Table
     |->receipt number
     |->account number
     |->receipt date
     |->receipt ID

 -->